#include <QSet>
#include "parameterlist.h"
#include "parameter.h"
#include "errorlog.h"

ParameterList::ParameterList(const YYLTYPE& loc)
        : Node(loc)
{
}

Parameter* ParameterList::parameter(const QString& name)
{
    Node* p = this->firstChild();
    while( p )
    {
        Parameter* param = dynamic_cast<Parameter*>(p);
        if ( param->name() == name )
            return param;
        p = p->nextSibling();
    }
    return 0;
}

QList<Parameter*> ParameterList::parameters()
{
    QList<Parameter*> result;

    Node* p = this->firstChild();
    while( p )
    {
        Parameter* param = dynamic_cast<Parameter*>(p);
        if ( param )
            result.append(param);
        p = p->nextSibling();
    }

    return result;
}

void ParameterList::resolveAll()
{
    this->Node::resolveAll();

    QSet<QString> names;
    Node* p = this->firstChild();
    while( p )
    {
        Parameter* param = dynamic_cast<Parameter*>(p);
        if ( names.contains(param->name()) )
            ErrorLog::error(param->location(), "Parameter " + param->name() + " is duplicated");
        else
            names.insert(param->name());
        p = p->nextSibling();
    }
}

Parameter* ParameterList::parameter(int index)
{
    int i = 0;
    Node* p = this->firstChild();
    while( p )
    {
        Parameter* param = dynamic_cast<Parameter*>(p);
        if ( param )
        {
            if ( i == index )
                return param;
            i++;
        }
        p = p->nextSibling();
    }
    return 0;
}
